#!/bin/bash
# dp Deployment Script for Linux
# Function: Deploy project to remote server

# Set UTF-8 encoding support
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

# Set script name for logging
SCRIPT_NAME="go_deploy_linux"

# ============================================
# Configuration and Global Variables
# ============================================

# Set working directory
export AWS="${AWS:-$HOME/workspace}"

# Log level: 0=ERROR, 1=WARN, 2=INFO, 3=DEBUG
LOG_LEVEL=${LOG_LEVEL:-2}

# Script directory
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# ============================================
# Utility Functions
# ============================================

# Log function
log() {
    local level=$1
    local message=$2
    local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    local level_str
    
    case $level in
        0) level_str="ERROR" ;;
        1) level_str="WARN"  ;;
        2) level_str="INFO"  ;;
        3) level_str="DEBUG" ;;
        *) level_str="UNKNOWN" ;;
    esac
    
    if [ $level -le $LOG_LEVEL ]; then
        echo "[$timestamp] [$SCRIPT_NAME] [$level_str] $message"
    fi
}

# Show separator
show_separator() {
    local char=${1:-"="}
    local length=${2:-50}
    printf "%*s\n" "$length" | tr ' ' "$char"
}

# Show title
show_title() {
    local title="$1"
    local char=${2:-"="}
    local total_width=60
    
    echo ""
    show_separator "$char" $total_width
    local title_len=${#title}
    local padding=$(( (total_width - title_len) / 2 ))
    printf "%*s%s%*s\n" $padding "" "$title" $padding ""
    show_separator "$char" $total_width
    echo ""
}

# Confirm action
confirm_action() {
    local message="$1"
    local default_yes=${2:-false}
    
    echo "$message"
    
    if [ "$default_yes" = true ]; then
        prompt="(Y/n): "
        default="y"
    else
        prompt="(y/N): "
        default="n"
    fi
    
    read -p "$prompt" response
    response=${response:-$default}
    
    case "$response" in
        [Yy]|[Yy][Ee][Ss])
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}

# ============================================
# Main Deployment Function
# ============================================

# dp deployment function implementation
dp_deploy_internal() {
    show_title "dp Deployment Function"

    log 2 "Starting dp deployment function..."
    echo "dp-bwg"

    # Set deploy variable
    local deploy="${AWS:-$HOME/workspace}/preDeploy"
    log 2 "Using deploy directory: $deploy"

    # Ensure deploy directory exists
    mkdir -p "$deploy"

    # 自动执行前端打包步骤
    log 2 "Executing frontend packaging step..."
    if [ -f "$SCRIPT_DIR/package_frontend.sh" ]; then
        # 设置deploy环境变量并执行打包脚本
        export deploy="$deploy"
        if "$SCRIPT_DIR/package_frontend.sh"; then
            log 2 "Frontend packaging completed successfully"
        else
            log 0 "Error: Frontend packaging failed"
            return 1
        fi
    else
        log 1 "Warning: package_frontend.sh not found, skipping auto packaging"
    fi

    # Create remote directory
    if ssh root@bwg "rm -rf /tmp/hk/trans && mkdir -p /tmp/hk/trans"; then
        log 2 "Remote directory /tmp/hk/trans created successfully"
    else
        log 1 "Warning: Unable to create remote directory /tmp/hk/trans"
    fi

    # Check if tmp.tar file exists
    local tmp_tar="$deploy/www_static/tmp.tar"
    
    # 创建tmp.tar文件，包含html和www_static目录
    if [ -d "$deploy" ]; then
        log 2 "Creating tmp.tar file..."
        (cd "$deploy" && tar -cf www_static/tmp.tar html www_static)
        if [ $? -eq 0 ]; then
            log 2 "tmp.tar file created successfully"
        else
            log 1 "Warning: Failed to create tmp.tar file"
        fi
    fi
    
    if [ -f "$tmp_tar" ]; then
        # Check file size
        local file_size="unknown"
        if command -v stat >/dev/null 2>&1; then
            file_size=$(stat -c%s "$tmp_tar" 2>/dev/null || stat -f%z "$tmp_tar" 2>/dev/null || echo "unknown")
        fi
        log 2 "File size of tmp.tar: $file_size bytes"

        log 2 "Transferring file..."
        # Transfer file
        if scp "$tmp_tar" root@bwg:/tmp/hk/trans/; then
            log 2 "File transfer completed successfully"

            log 2 "Extracting and executing deployment script..."
            # Extract and execute deployment script on remote server
            # 注意：这里使用www_static目录，因为这是包含部署脚本的目录
            if ! ssh root@bwg "cd /tmp/hk/trans/ && tar -xvf tmp.tar && cd www_static && chmod 700 *.sh && ./goHtmlLinux.sh && cd .. && rm -rf www_static"; then
                log 1 "Warning: Remote deployment script execution failed"
            fi
        else
            log 1 "Warning: File transfer failed"
        fi
    else
        log 1 "Warning: tmp.tar file does not exist, skipping HTML deployment"
    fi

    log 2 "dp deployment completed"
    echo ""
    echo "✅ dp deployment completed successfully!"
    echo ""
    
    # Wait for 5 seconds to allow user to read the logs
    log 2 "Waiting for 5 seconds to allow user to read the logs..."
    sleep 5

    return 0
}

# Show help information
show_help() {
    echo "dp Deployment Tool"
    echo ""
    echo "Usage: $0 [options]"
    echo ""
    echo "Function: Deploy project to remote server"
    echo ""
    echo "Options:"
    echo "  --help, -h        Show this help message"
    echo ""
    echo "Environment variables:"
    echo "  AWS        Working directory (default: \$HOME/workspace)"
    echo "  LOG_LEVEL  Log level (0=ERROR, 1=WARN, 2=INFO, 3=DEBUG)"
    echo ""
}

# Main function
main() {
    # Get command parameters
    local subcommand="$1"
    
    # Process different commands
    case "$subcommand" in
        "help"|"--help"|"-h")
            show_help
            ;;
        "")
            # No parameters, execute deployment
            dp_deploy_internal
            ;;
        *)
            # Unknown command
            log 0 "Error: Unknown command $subcommand"
            show_help
            return 1
            ;;
    esac
    
    return $?
}

# Execute main function
main "$@"